package com.soriya.nestlive.common;

import com.soriya.nestlive.constant.CommonConst;
import com.soriya.nestlive.entity.ChannelEntity;
import com.soriya.nestlive.service.ChannelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class RedisKeyExpirationHandler extends KeyExpirationEventMessageListener {

    private final ChannelService channelService;

    public RedisKeyExpirationHandler(RedisMessageListenerContainer listenerContainer, ChannelService channelService) {
        super(listenerContainer);
        this.channelService = channelService;
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = message.toString();

        if (key.startsWith(CommonConst.REDIS_KEY_PREFIX + CommonConst.STREAMING_PREFIX)) {
            Long channelId = Long.parseLong(key.substring((CommonConst.REDIS_KEY_PREFIX + CommonConst.STREAMING_PREFIX).length()));
            log.info("Live Sign out: {}", channelId);
            ChannelEntity channelEntity = new ChannelEntity();
            channelEntity.setId(channelId);
            channelEntity.setLiveState(0);
            channelService.updateById(channelEntity);
        }

        log.info("Redis Key Ex: {} -- body: {}", key, new String(message.getChannel()));
    }
}
